package com.king.framework.base.controller;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import com.king.common.annotation.MvcData;
import com.king.common.constant.HttpStatus;
import com.king.common.exception.AssertHelper;
import com.king.common.utils.SecurityUtils;
import com.king.framework.base.domain.vo.AjaxResult;
import com.king.framework.base.domain.vo.PageResult;
import com.king.framework.base.service.YyBaseService;

public class YyBaseController<T> extends BaseController {
	
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    protected Class<T> persistentClass;
    
    
    @Autowired
    protected YyBaseService<T, Long> baseService;
    
    
    
    @SuppressWarnings("unchecked")
    protected void init() {
        // 当前对象的直接超类的 Type
        Type genericSuperclass = getClass().getGenericSuperclass();
        if (genericSuperclass instanceof ParameterizedType) {
            // 参数化类型
            ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
            // 返回表示此类型实际类型参数的 Type 对象的数组
            Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
            this.persistentClass = (Class<T>) actualTypeArguments[0];
        } else {
            this.persistentClass = (Class<T>) genericSuperclass;
        }
    }
    
    
    /**
     * 处理查询条件-用于重写
     *
     * @param searchMap
     * @param request
     * @return
     * @throws Exception
     * @author yy-team
     */
    protected Map<String, Object> dealSearch(HttpServletRequest request, Map<String, Object> searchMap) throws Exception {
        return searchMap;
    }

    /**
     * 此处添加查询参数,用Map替代null
     * 格式：LIKE_usercode=aa key和value都是String类型的。 addParam.put("LIKE_usercode", "aa");
     * 可以添加排序，格式
     * addParam.put("EQ_validDate", "2014-10-01");
     *
     * @return
     */
    protected Map<String, Object> addSearchParam(HttpServletRequest request) throws Exception {
        Map<String, Object> addParam = new HashMap<String, Object>();
        if(!SecurityUtils.isAdmin()){
        	addParam.put("EQ_groupid", SecurityUtils.getGroupid());
        }
        return addParam;
    }
    
    
//    protected void beforeQuery(HttpServletRequest request, @RequestBody(required = false) Map<String, Object> searchMap) throws Exception {
//    }
    
    /**
     * 判断权限
     */
    protected void checkPermission(){
		AssertHelper.getInstance().checkException(!SecurityUtils.isAdmin(), "没有权限");
    }
    
    /*
     * 根据id查找
     */
    @MvcData("获取")
    @GetMapping("/get/{id}")
    public AjaxResult get(@PathVariable("id") Long id) throws Exception {
        T entity = baseService.findByPK(id);
        if (entity == null) {
           return error("没有数据");
        }
        return success(entity);
    }
    
    
    /**
     * 通用查询
     *
     * @param request
     * @param searchMap
     * @return
     * @throws Exception
     */
    @MvcData("查询")
    @PreAuthorize("@sps.hasAuthority('*:*:query')")
    @PostMapping(value = "/query")
    public AjaxResult query(HttpServletRequest request, @RequestBody(required = false) Map<String, Object> searchMap) throws Exception {
//    	beforeQuery(request, searchMap);
    	
        searchMap.putAll(addSearchParam(request));
        dealSearch(request, searchMap);
        
        PageResult<T> datas = baseService.doQuery(searchMap);
        return success(datas);
    }
    

    /*
     * 删除记录
     */
    @MvcData("删除")
    @GetMapping("/delete/{id}")
    public AjaxResult deleteOne(HttpServletRequest request, @PathVariable("id") Long id) throws Exception {
        baseService.doDelete(id);
        return success("操作成功");
    }

    /*
     * 批量删除
     *
     */
    @MvcData("批量删除")
    @PostMapping(value = "/delete")
    public AjaxResult delete(HttpServletRequest request, @RequestBody(required = false) Long[] ids) throws Exception {
        if (ids == null || ids.length == 0) {
            return new AjaxResult(HttpStatus.ERROR, "删除失败：请选择删除的记录");
        }
        baseService.doDelete(ids);
        return success("操作成功");
    }

   

    /*
     * 新增保存
     *
     */
    @MvcData("新增")
    @PostMapping("/add")
    public AjaxResult add(HttpServletRequest request, @RequestBody T entity) throws Exception {
        entity = baseService.doAdd(entity);
        return success(entity);
    }

    
    /*
     * 仅仅更新不为null的字段，如果字段为null，则不更新该字段值
     */
    @MvcData("更新")
    @PostMapping("/update")
    public AjaxResult update(HttpServletRequest request, @RequestBody T entity) throws Exception {
        if (entity == null) {
            logger.error("实体" + persistentClass.getName() + "不存在，更新失败：可能是id为空，获取不到实体");
            return new AjaxResult(HttpStatus.ERROR, "实体" + persistentClass.getName() + "不存在，更新失败！");
        }
        entity = baseService.doUpdate(entity);
        return success(entity);
    }




}
